package com.base.lock;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

/**
 * @Author HBZ
 * @Date 2020/9/28 17:22
 * @Description
 */
public class MyLock implements Lock {
    AtomicReference<Thread> owner = new AtomicReference<>();
    LinkedBlockingQueue waiters = new LinkedBlockingQueue<Thread>();

    @Override
    public void lock() {
        Thread thread=Thread.currentThread();
        while (!owner.compareAndSet(null,thread )){
           waiters.add(thread);
            LockSupport.park();
            waiters.remove(thread);
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        if(owner.get()==Thread.currentThread()){
            owner.set(null);
            for(Object o:waiters.toArray()){
                Thread next=(Thread)o;
                LockSupport.unpark(next);
            }
        }
      /*  // 只有持有锁的线程才能解锁
        if(owner.compareAndSet(Thread.currentThread(),null )){
            // 唤醒其他线程
            for(Object o:waiters.toArray()){
                Thread next=(Thread)o;
                LockSupport.unpark(next);
            }
        }
        else{
            // 失败不做处理
        }*/
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
